package com.zxj.netty.zookeeper;

import com.google.common.collect.Lists;
import com.zxj.netty.client.RpcClient;
import com.zxj.netty.client.ChannelManager;
import io.netty.channel.ChannelFuture;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.zookeeper.WatchedEvent;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 每次远程节点变更都重新加载所有节点到本地缓存
 */
public class ServerWatcher implements CuratorWatcher {
    @Override
    public void process(WatchedEvent watchedEvent) throws Exception {
        // 被监控节点路径
        String eventPath = watchedEvent.getPath();
        ZookeeperFactory.getZookeeperClient().getChildren().usingWatcher(this).forPath(eventPath);
        // 已注册节点路径 192.168.167.1#0000000016
        List<String> pathList = ZookeeperFactory.getZookeeperClient().getChildren().forPath(eventPath);
        Set<String> urlSet = new HashSet<>();
        // 重新设置本地缓存节点url
        for (String path : pathList) {
            String url = path.split("#")[0];
            urlSet.add(url);
        }

        Set<String> systems = ChannelManager.SYSTEMS;
        for (String sys : systems) {
            // 对应远程系统注册节点变化则重新建立连接
            if (!eventPath.contains(sys)) {
                continue;
            }
            List<ChannelFuture> channelFutures = Lists.newArrayList();
            for (String url : urlSet) {
                ChannelFuture future = RpcClient.connect(url);
                channelFutures.add(future);
            }
            // 重新缓存本地连接
            ChannelManager.add(sys, channelFutures);
        }
    }
}
